package cn.kgc.fxy.smbms.web;

import cn.kgc.fxy.smbms.entity.Role;
import cn.kgc.fxy.smbms.entity.User;
import cn.kgc.fxy.smbms.service.Constant;
import cn.kgc.fxy.smbms.service.RoleService;
import cn.kgc.fxy.smbms.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;
    @RequestMapping("/show")
    public String show(User condition, Integer pageNum, Model model){
        Integer pageSize = 5;
        PageInfo<User> userPageInfo = this.userService.findAllUser(condition,pageNum,pageSize);
        List<Role> roleList = this.roleService.findByRoleName();
        model.addAttribute("roleList",roleList);
        model.addAttribute("pageInfo",userPageInfo);
//        int i=1/0;
        return "user/list";
    }
    @ExceptionHandler
    public String handlerException(Throwable throwable, HttpServletRequest request){
        request.setAttribute("exception",throwable.getMessage());
        return "error";
    }

    @RequestMapping("/view")
    public String view(Long userId,Model model){
        User user = this.userService.findView(userId);
        System.out.println("user = " + user.getUserName());
        model.addAttribute("user",user);
        return "user/view";
    }


    @RequestMapping("/toAdd")
    public String toAdd(Model model,User user){
        List<Role> roleList = this.roleService.findByRoleName();
        model.addAttribute("roleList",roleList);
        return "user/add";
    }
    //用户角色
    private void fetchRoleList(Model model){
        List<Role> roleList = this.roleService.findByRoleName();
        model.addAttribute("roleList",roleList);
    }

    @RequestMapping("/doAdd")
    public String doAdd(@Valid User user, BindingResult bindingResult, HttpSession session,
                        Model model, MultipartFile[] pic) throws Exception {
        if (bindingResult.hasErrors()){
            fetchRoleList(model);
            return "user/add";
        }
        List<String>  allowedFileExtendsName= Arrays.asList(".jpg",".png",".gif",".jpeg");
        for(MultipartFile thePic:pic) {
            String extendsName = thePic.getOriginalFilename().substring(thePic.getOriginalFilename().lastIndexOf("."));
            if (allowedFileExtendsName.contains(extendsName.toLowerCase()) == false) {
                throw new Exception("文件扩展名不被允许,允许: .jpg,.png,.gif,.jpeg");
            }

            if (thePic.isEmpty() == false) {
                String serverDirectory = session.getServletContext().getRealPath(File.separator + "headPic");
                System.out.println("serverDirectory = " + serverDirectory);
                System.out.println("pic.getOriginalFilename() = " + thePic.getOriginalFilename());
                String fileName = System.currentTimeMillis() + "-" + new Random().nextInt(9999) + "-head"
                        + thePic.getOriginalFilename().substring(thePic.getOriginalFilename().lastIndexOf("."));
                File destination = new File(serverDirectory, fileName);
                thePic.transferTo(destination);
                user.setUserPicName(fileName);
            }
        }
        User loginUser = (User) session.getAttribute(Constant.USER);
        user.setCreatedBy(loginUser);
        user.setCreationDate(new java.util.Date());
        this.userService.addUser(user);
        return "redirect:show";
    }
    @RequestMapping(value = "/showUser/{userId}")
    @ResponseBody
    public Object showUser(@PathVariable Long userId){
        User user=this.userService.findById(userId);
        return user;
//        String jsonString=JSON.toJSONString(user);
//        return jsonString;
    }

    @RequestMapping("/showUserCount")
    @ResponseBody
    public String showUserCount(String userCode){
        Integer userCount = this.userService.findUserCount(userCode);
        return userCount.toString();

    }
    @RequestMapping("/toModify")
    public String toModify(Model model,Long userId){
        fetchRoleList(model);
        User user = userService.findView(userId);
        model.addAttribute("user",user);
        return "user/modify";
    }
    @RequestMapping("/doModify")
    public String doModify(@Valid User user,BindingResult bindingResult,Model model){
        if (bindingResult.hasErrors()){
            fetchRoleList(model);
            return "user/modify";
        }
        userService.modifyUser(user);
        return "redirect:show";
    }

    @RequestMapping("/toRemove")
    public String toRemove(Long userId){
        this.userService.removeUser(userId);
        return "redirect:show";
    }
}
